<template>
  <div class="main-box">
    <div class="table-box">
      <ProTable
        :columns="colums"
        ref="ProRef"
        :init-param="initParams"
        :data-callback="dataCallback"
        :request-api="GetAccountList"
      >
        <template #tableHeader="scope">
          <el-button type="primary" @click="operaAccount(undefined)" v-auth="'新增账号'">新增用户</el-button>
          <el-button
            type="danger"
            :disabled="scope.selectedListIds.length === 0"
            v-auth="'删除账号'"
            @click="deleteAccount(scope.selectedListIds)"
            >批量删除</el-button
          >
        </template>
        <template #avatar="{ row }">
          <el-image fit="fill" :src="row.avatar"></el-image>
        </template>
        <template #idCard></template>
        <template #create_time="{ row }">
          {{ dayjs(row.create_time).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
        <template #status="{ row }">
          <el-switch
            active-text="启用"
            inactive-text="停用"
            v-auth="'状态'"
            v-model="row.status"
            @change="changeStatus(row)"
          ></el-switch>
        </template>
        <template #is_set_region="{ row }">
          <el-tag type="success" v-show="row.is_set_region">是</el-tag>
          <el-tag type="danger" v-show="!row.is_set_region">否</el-tag>
        </template>
        <template #opera="{ row }">
          <div>
            <el-button link type="primary" @click="operaAccount(row)" v-auth="'编辑账号'">编辑</el-button>
            <el-button link type="primary" @click="changeCall(row)" v-auth="'编辑账号'">修改手机</el-button>
            <el-button link type="primary" @click="changeCard(row)" v-auth="'编辑账号'">修改实名</el-button>
            <el-button link type="primary" @click="deleteAccount([row.id])" v-auth="'删除账号'">删除</el-button>
          </div>
        </template>
      </ProTable>
    </div>
    <changeIDCard ref="idCardRef"></changeIDCard>
    <accountDrawer ref="accountRef"></accountDrawer>
    <change-phone ref="changePhoneRef"></change-phone>
  </div>
</template>

<script setup lang="ts" name="accountManage">
import ProTable from "@/components/ProTable/index.vue";
import { GetAccountList } from "@/api/modules/account";
import { reactive, ref, onBeforeMount } from "vue";
import { ColumnProps } from "@/components/ProTable/interface";
import dayjs from "dayjs";
import accountDrawer from "./components/accountDrawer.vue";
import { AddAccount, editAccount } from "@/api/modules/account";
import { GetRoleList } from "@/api/modules/role";
import { Role } from "@/api/interface/role";
import { Region } from "@/api/interface/region";
import { deleteAccount as deleteApi, setStatus } from "@/api/modules/account";
import { useHandleData } from "@/hooks/useHandleData";
import changePhone from "./components/changePhone.vue";
import changeIDCard from "./components/changeIDCard.vue";

// 修改手机
const changePhoneRef = ref<InstanceType<typeof changePhone> | null>();

const changeCall = (row: any) => {
  const params: any = {
    row,
    getTable: ProRef.value?.getTableList
  };
  changePhoneRef.value?.open(params);
};

// 修改实名
const idCardRef = ref<InstanceType<typeof changeIDCard> | null>();

const changeCard = (row: any) => {
  const params: any = {
    row,
    getTable: ProRef.value?.getTableList
  };
  idCardRef.value?.open(params);
};

const dataCallback = (data: any) => {
  const newData = data;
  newData.list = data.list.filter((e: any) => !e.role.is_broker);
  return newData;
};

const changeStatus = async (row: any) => {
  await setStatus(row);
};

// -----表格数据
const initParams = reactive({ id: "" });
const regionType = ref(""); // 地区类型

// -------表格
let colums: ColumnProps[] = [
  { type: "selection", fixed: "left", width: 50 },
  { prop: "sort", label: "排序值", width: 100, fixed: "left" },
  { prop: "username", label: "账号名称", fixed: "left", search: { el: "input" } },
  { prop: "realName", label: "用户名", search: { el: "input" } },
  { prop: "openId", label: "openId", width: 200 },
  { prop: "roleName", label: "角色" },
  {
    prop: "status",
    label: "状态",
    search: {
      el: "switch",
      props: { "active-value": true, "active-text": "启用", "inactive-value": false, "inactive-text": "停用" },
      defaultValue: true
    }
  },
  {
    prop: "roleId",
    label: "角色身份",
    isShow: false,
    search: { el: "cascader", props: { props: { checkStrictly: true, emitPath: false } } },
    enum() {
      return GetRoleList({ status: 2 });
    },
    fieldNames: { label: "roleName", value: "id", children: "roles" }
  },
  { prop: "phone", label: "手机号", search: { el: "input" } },
  {
    prop: "create_time",
    label: "创建时间",
    search: { el: "date-picker", props: { type: "daterange", valueFormat: "YYYY-MM-DD" }, span: 2 }
  },
  { prop: "opera", label: "操作", width: 350, fixed: "right" }
];

// -----------可以设置区域的账号，以当前可以选择的地区为基准
const selectRegion = ref<"country" | "province" | "city" | "district" | "custom" | undefined>();
// const getCanOperaRegion = (
//   type: "country" | "province" | "city" | "district" | "custom"
// ): "country" | "province" | "city" | "district" | "custom" | undefined => {
//   if (type === "country") return "province";
//   if (type === "province") return "city";
//   if (type === "city") return "district";
//   if (type === "district") return "custom";
//   if (type === "custom") return undefined;
// };

const ProRef = ref<InstanceType<typeof ProTable> | null>();

// 客户操作
const accountRef = ref<InstanceType<typeof accountDrawer> | null>();

const operaAccount = (row: any, disabled: boolean = false) => {
  // 获取当前选择
  const params: any = {
    rowData: row,
    getTable: ProRef.value?.getTableList,
    roleList: roleList.value[0].roles,
    api: row ? editAccount : AddAccount,
    pid: initParams.id,
    regionType: regionType.value,
    disabled
  };
  accountRef.value?.acceptParams(params);
};

// 获取角色列表
const roleList = ref<Role.Option[]>([]);

const flatArea = ref<any[]>([]); //扁平化后的地区
const canSetRegion = ref<Region.Option[]>([]); //当前可以选择区域
const initCanSetRegion = () => {
  canSetRegion.value =
    initParams.id === ""
      ? flatArea.value.filter((e: Region.Option) => e.level === selectRegion.value)
      : flatArea.value.filter((e: Region.Option) => e.pid === parseInt(initParams.id));
};

const deleteAccount = async (ids: any) => {
  await useHandleData(deleteApi, { ids }, "删除所选用户信息");
  ProRef.value?.clearSelection();
  ProRef.value?.getTableList();
};

onBeforeMount(async () => {
  roleList.value = (await GetRoleList({ status: 2 })).data as any;
  // selectRegion.value = getCanOperaRegion(roleList.value[0].regionType);
  initCanSetRegion();
});
</script>
